#include <ixwebsocket/IXWebSocketServer.h>
#include <ixwebsocket/IXNetSystem.h>
#include <iostream>
#include <string>

int main() {
    // 初始化网络系统（Windows平台需要）
    ix::initNetSystem();

    // 创建WebSocket服务器，监听8080端口
    int port = 8080;
    std::string hostname = "0.0.0.0";
    ix::WebSocketServer server(port, hostname);

    // 设置连接回调 - 使用正确的签名
    server.setOnClientMessageCallback(
        [&server](std::shared_ptr<ix::ConnectionState> connectionState,
                  ix::WebSocket& webSocket,
                  const ix::WebSocketMessagePtr& msg) {
            if (msg->type == ix::WebSocketMessageType::Open) {
                std::cout << "New connection from: " << connectionState->getRemoteIp() 
                          << " (ID: " << connectionState->getId() << ")" << std::endl;
            }
            else if (msg->type == ix::WebSocketMessageType::Message) {
                std::cout << "Received message from client " 
                          << connectionState->getId() << ": " << msg->str << std::endl;

                // 将消息发送回给发送者（回声）
                webSocket.send(msg->str);
                
                // 或者广播给所有连接的客户端
                // server.broadcast(msg->str);
            }
            else if (msg->type == ix::WebSocketMessageType::Close) {
                std::cout << "Client disconnected: " << connectionState->getId() << std::endl;
            }
            else if (msg->type == ix::WebSocketMessageType::Error) {
                std::cout << "Error: " << msg->errorInfo.reason << std::endl;
            }
        });

    // 启动服务器
    auto res = server.listen();
    if (!res.first) {
        std::cerr << "Error starting server: " << res.second << std::endl;
        return 1;
    }

    server.start();
    std::cout << "Server listening on " << hostname << ":" << port << "..." << std::endl;

    // 保持服务器运行
    std::cout << "Press Enter to exit." << std::endl;
    std::string line;
    std::getline(std::cin, line);

    server.stop();
    ix::uninitNetSystem();

    return 0;
}
